package com.gzzyy.facerecognition.http

import android.util.Log
import com.gzzyy.facerecognition.bean.HumanDataBean
import com.gzzyy.facerecognition.bean.HumanInfoBean
import com.gzzyy.facerecognition.bean.UrlBean
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import retrofit2.HttpException
import java.io.File
import java.net.SocketTimeoutException
import java.net.UnknownHostException


object SuspendRequest {
    private suspend fun <T> request(call: suspend () -> DataResponse<T>): DataResponse<T> {
        try {
            return withContext(Dispatchers.IO) {
                call.invoke()
            }
        } catch (e: Exception) {
            val clz = e::class.java
            Log.e("error", "异常类名:${clz.simpleName}")
            Log.e("error", e.message ?: "未知异常")
            when (e) {
                is HttpException -> return DataResponse(
                    e.code(),
                    e.message()
                )
                is SocketTimeoutException -> return DataResponse(
                    -1,
                    "请求超时"
                )
                is UnknownHostException -> return DataResponse(
                    600,
                    "网络异常"
                )
                else -> return DataResponse(
                    601,
                    "未知异常"
                )
            }
        }
    }

    suspend fun upLoadImage(file: File): DataResponse<UrlBean?> = request {
        val photoRequestBody = RequestBody.create("image/jpg".toMediaTypeOrNull(), file)
        val photoPart = MultipartBody.Part.createFormData("file", file.name, photoRequestBody)
        RetrofitClient.httpApi.uploadImage(photoPart)
    }

    suspend fun upLoadUrl(image: String): DataResponse<HumanDataBean?> = request {
        RetrofitClient.httpApi.uploadUrl(image)
    }


}